package com.hrvsr.session.useragent;

import java.io.Closeable;
import java.io.IOException;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisUserAgentPool extends AbstractNotNullUserAgentPool implements Closeable {

	private JedisPool jedisPool;

	public JedisPool getJedisPool() {
		return jedisPool;
	}

	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

	public int getDbNo() {
		return dbNo;
	}

	public void setDbNo(int dbNo) {
		this.dbNo = dbNo;
	}

	public String getQueue() {
		return queue;
	}

	public void setQueue(String queue) {
		this.queue = queue;
	}

	private int dbNo;
	private String queue;

	@Override
	public String poll() {
		Jedis jedis = jedisPool.getResource();
		try {
			jedis.select(dbNo);
			String userAgnet = jedis.rpoplpush(queue, queue);
			return notNullAgent(userAgnet);
		} catch (Exception e) {
			return DEFAUTL_USER_AGENT;
		} finally {
			jedis.close();
		}
	}

	@Override
	public void offer(String userAgent) {
		Jedis jedis = jedisPool.getResource();
		try {
			jedis.select(dbNo);
			jedis.lpush(queue, userAgent);
		} finally {
			jedis.close();
		}
	}

	@Override
	public void close() throws IOException {
		if (jedisPool != null) {
			jedisPool.close();
		}
	}
}
